package com.mlick.a.java8.juc;

import java.util.Arrays;
import java.util.Objects;
import java.util.concurrent.*;

/**
 * @author lixiangxin
 * @date 2019/3/30 10:00
 **/
public class CompleteService {


    private final static ExecutorService EXECUTOR_SERVICE = Executors.newCachedThreadPool();

    private CompletionService<Boolean> completionService = new ExecutorCompletionService<>(EXECUTOR_SERVICE);

    void validParams(Object... params) {
        Arrays.stream(params).forEach(param -> {
            if (Objects.isNull(param)) {
                throw new RuntimeException("Parameter can't be empty");
            }
        });
    }

    public void valid32Name(String name) {
        if (name.length() > 30) {
            throw new RuntimeException("Parameter violation");
        }
    }

    public void testExec() {

        completionService.submit(new Callable<Boolean>() {
            @Override
            public Boolean call() throws Exception {
                System.out.println(Thread.currentThread().getName() + "=>1");
                try {
                    validParams("111");
                } catch (Exception e) {
                    EXECUTOR_SERVICE.shutdown();
                    throw e;
                }

                System.out.println(Thread.currentThread().getName() + "=>2");
                validParams(null);
                System.out.println(Thread.currentThread().getName() + "=>3");
                return true;
            }
        });
        completionService.submit(new Callable<Boolean>() {
            @Override
            public Boolean call() throws Exception {
                System.out.println(Thread.currentThread().getName() + "=>4");
                valid32Name("1111111111112222222222223333333333333333");
                System.out.println(Thread.currentThread().getName() + "=>5");
                return true;
            }
        });


        try {
            System.out.println(completionService.take().get());
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }

    }


    public static void main(String[] args) {
        new Thread(()->new CompleteService().testExec()).start();
//        new Thread(()->new CompleteService().testExec()).start();


    }

}
